package com.hrt.manage.role.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.hrt.base.BaseDaoImpl;
import com.hrt.bean.Role;
import com.hrt.bean.UserRoles;
import com.hrt.manage.role.dao.UserRoleDao;

@Repository
public class UserRoleDaoImpl extends BaseDaoImpl<UserRoles> implements
		UserRoleDao {

	@Override
	public List<Role> queryRolesByUserId(Long userId) {
		List<Role> result=new ArrayList<Role>();
		
		String hql="SELECT r FROM Role r WHERE r.id IN(select ur.roleId from UserRoles ur where ur.isdelete=0 and ur.userId="+userId+")"; 
		result=	this.getHibernateTemplate().find(hql);
		return result;
	}

	@Override
	public UserRoles getUserRoleById(Long userId, Long roleId) {
		
		final String hql="select  ur  from UserRoles ur where ur.isdelete=0 and ur.userId="+userId+" and ur.roleId="+roleId+"";
		UserRoles result=	this.getHibernateTemplate().execute(new HibernateCallback<UserRoles>(){

			@Override
			public UserRoles doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Query query=session.createQuery(hql);
				return (UserRoles) query.uniqueResult();
			}
			
		});
		return result;
	}

}
